<?php
class lib_company extends lib_base{
	public $table_name = "qc_company";
    public $pk = "id";


    public function get_site($id)
    {
        $info = $this->findById($id);

		$cond = "company_id='{$id}' and is_admin=1 and status=1";
		$info['admin'] = D('company_admin')->find(array($cond));
        return $info;
    }

    public function add_site($data)
    {
        $arrBase = array(
            // 'area_id'=> $data['area_id'],
            'site_id'=> $data['site_id'],
            'name' => $data['name'],
            'sort' => $data['sort'],
            'add_time' => date('Y-m-d H:i:s'),
            'status'=>1,
        );
        $site_id = $this->create($arrBase);
        if($site_id){
            $arrBase = array(
                'company_id' => $site_id,
                'username' => $data['username'],
                'password' => qcing_hash($data['password']),
                'realname' => '站点管理员',
                'is_admin'=>1,
                'add_time' => date('Y-m-d H:i:s'),
                'status'=>1,
            );
            D('company_admin')->create($arrBase);
            return true;
        }
    }

    public function edit_site($id,$data)
    {
        $arrBase = array(
            // 'area_id'=> $data['area_id'],
            'name' => $data['name'],
            'sort' => $data['sort'],
        );
        $this->update(array("{$this->pk}"=>$id), $arrBase);

        $arrBase = array(
            'username' => $data['username'],
            'password' => qcing_hash($data['password']),
        );
        $cond = "is_admin=1 and status=1 and company_id={$id}";
        D('company_admin')->update(array($cond), $arrBase);
        return true;
    }


    public function del_site($site_id=0)
    {
        if($site_id){
            $this->delete(array("id IN ({$site_id})"));
            D('company_admin')->del_user($site_id);
        }
        return true;
    }

    public function auth($site_id,$data,$ids)
    {
        $arrBase[$ids] = joinStr($data);
        return $this->edit($site_id, $arrBase);
    }

    public function get_setting($id,$val=''){
        $res = $this->findById($id);
        $setting = unserialize($res['setting']);
        if($val){
            return $setting[$val];
        }
        return $setting;
    }

    public function set_setting($id,$val='',$data){
        $res = $this->findById($id);
        $setting = unserialize($res['setting']);
        $setting[$val] = $data;
        $this->update(array('id'=>$id), array('setting'=>serialize($setting)));
        return true;
    }

}